<script lang="ts" setup>
import {reactive, ref, watch} from "vue";
import DataSourceInfoVO from "@/domain/vo/DataSourceInfoVO";
import dataSourceService from "@/service/DataSourceService";
import DataSourceInfoFormBO from "@/domain/bo/DataSourceInfoFormBO";
import {ElMessage, FormInstance, FormRules} from "element-plus";
import GlobalConstant from "@/domain/constants/GlobalConstant";
import SelectConstant from "@/domain/constants/SelectConstant";
import StringUtils from "@/utils/StringUtils";

const props = defineProps({
  dataSourceInfoVO: {
    type: DataSourceInfoVO,
    required: true
  },
  dialogVisible: {
    type: Boolean,
    required: true
  }
});
//========================== 按钮事件 ==========================
const testConnectionRes = ref(-1);

function testConnection() {
  if (StringUtils.isNotBlank(dataSourceInfoFormBO.password)) {
    dataSourceService.testConnection(dataSourceInfoFormBO)
        .then((res) => {
          if (res) {
            testConnectionRes.value = 1;
          } else {
            testConnectionRes.value = 0;
          }
        }, (res) => {
          testConnectionRes.value = 0;
        });
  } else {
    dataSourceService.testConnectionById(dataSourceInfoFormBO.id)
        .then((res) => {
          if (res) {
            testConnectionRes.value = 1;
          } else {
            testConnectionRes.value = 0;
          }
        }, (res) => {
          testConnectionRes.value = 0;
        })
  }
}

function closeDialog() {
  props.dialogVisible = false;
}

async function saveDataSourceInfo() {
  let flag = false;
  if (StringUtils.isBlank(dataSourceInfoFormBO.id as string)) {
    await dataSourceService.add(dataSourceInfoFormBO)
        .then(
            (res) => {
              props.dialogVisible = false;
              ElMessage.success(GlobalConstant.SAVE_SUCCESS_MSG);
              flag = true;
            }, (error) => {
              ElMessage.error(GlobalConstant.SAVE_ERROR_MSG + error.msg);
            }
        )
  } else {
    await dataSourceService.edit(dataSourceInfoFormBO)
        .then(
            (res) => {
              props.dialogVisible = false;
              ElMessage.success(GlobalConstant.EDIT_SUCCESS_MSG);
              flag = true;
            },
            (error) => {
              ElMessage.error(GlobalConstant.SAVE_ERROR_MSG + error.msg);
            }
        )
  }
  return flag;
}

//========================== watch监听 ==========================
const dataSourceInfoFormBO = reactive(new DataSourceInfoFormBO());
watch(
    () => props.dialogVisible,
    (o, n) => {
      if (!n) { //由false改为true表示显示，需要渲染内容
        testConnectionRes.value = -1;
        dataSourceInfoFormBO.coverFormDataSourceInfoVO(props.dataSourceInfoVO)
      }
    }
)

//========================== 回调事件 ==========================
const emits = defineEmits(["closeAfter", "saveAfter"])

function closeHandle() {
  closeDialog();
  emits("closeAfter");
}

function saveHandle(ruleFormRef: FormInstance) {
  ruleFormRef.validate((valid) => {
    if (valid) {
      saveDataSourceInfo()
          .then((flag) => {
            if (flag) {
              emits("saveAfter");
            }
          })
    }
  })
}

//========================== 表单校验规则 ==========================
const ruleFormRef = ref<FormInstance>()
const rules = reactive<FormRules<DataSourceInfoFormBO>>({
  databaseType: [
    {
      required: true,
      message: '必填',
      trigger: 'blur'
    },
  ],
  host: [
    {
      required: true,
      message: '必填',
      trigger: 'blur',
    },
  ],
  password: [
    {
      required: true,
      message: '必填',
      trigger: 'blur',
    },
  ],
  port: [
    {
      required: true,
      message: '必填',
      trigger: 'blur',
    },
  ],
  schemaName: [
    {
      required: true,
      message: '必填',
      trigger: 'blur',
    },
  ],
  username: [
    {
      required: true,
      message: '必填',
      trigger: 'blur',
    },
  ],
})
</script>
<template>
  <div>
    <el-dialog
        v-model="props.dialogVisible"
        title="Tips"
        width="30%"
        :close-on-click-modal="false"
        :before-close="closeHandle"
    >
      <template #title>
        <template v-if="props.mysqlTableColumnMapVO?.id === undefined">
          <span>新增</span>
        </template>
        <template v-else>
          <span>编辑</span>
        </template>
      </template>
      <el-form
          ref="ruleFormRef"
          :rules="rules"
          :model="dataSourceInfoFormBO"
          label-width="120px"
          class="demo-ruleForm"
          status-icon
      >
        <el-form-item prop="databaseType" label="数据库类型">
          <el-select v-model="dataSourceInfoFormBO.databaseType">
            <el-option
                v-for="item in SelectConstant.DATABASE_TYPE"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item prop="host" label="Host" placeholder="localhost">
          <el-input v-model="dataSourceInfoFormBO.host"/>
        </el-form-item>
        <el-form-item prop="port" label="Port">
          <el-input v-model="dataSourceInfoFormBO.port"/>
        </el-form-item>
        <el-form-item prop="schemaName" label="连接数据库">
          <el-input v-model="dataSourceInfoFormBO.schemaName"/>
        </el-form-item>
        <el-form-item prop="username" label="用户名">
          <el-input v-model="dataSourceInfoFormBO.username"/>
        </el-form-item>
        <el-form-item label="密码">
          <el-input v-model="dataSourceInfoFormBO.password"
                    type="password"
                    placeholder="设置新密码"
                    show-password/>
        </el-form-item>
        <el-form-item>
          <el-button @click="testConnection">测试连接</el-button>
          <template v-if="testConnectionRes == 1">
            <span style="color: green">连接成功</span>
          </template>
          <template v-else-if="testConnectionRes == 2">
            <span style="color: red">连接失败</span>
          </template>
        </el-form-item>
      </el-form>
      <template #footer>
      <span class="dialog-footer">
        <el-button @click="closeHandle(ruleFormRef)">
          关闭
        </el-button>
        <el-button type="primary" @click="saveHandle(ruleFormRef)">
          保存
        </el-button>
      </span>
      </template>
    </el-dialog>
  </div>
</template>
<style lang="scss" scoped>

</style>